package com.hainatong.shiphelper.module.QSHE;


import android.app.Activity;
import android.content.Intent;


import android.os.Bundle;

import android.text.TextUtils;
import android.view.View;


import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.snackbar.Snackbar;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.TestViewModel;
import com.hainatong.shiphelper.databinding.ActivityFileReaderBinding;



import com.hainatong.shiphelper.widget.FileReaderView;
import com.hainatong.mvvmbase.base.BaseMvvmActivity;


import com.hainatong.mvvmbase.loadsir.layoutcallback.*;
import com.xuexiang.xaop.cache.XDiskCache;
import com.xuexiang.xutil.file.FileUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import okhttp3.Call;
import okhttp3.Request;

import java.io.File;


public class FileReaderActivity extends BaseMvvmActivity<ActivityFileReaderBinding, TestViewModel>
{
    private static String FILE_URL_TAG = "FILE_URL";

    private String fileUrl;

    //private LoadService loadSer;

    public static void start(Activity context, String url)
    {
        if(StringUtils.isEmpty( url ))
        {
            start(context,null,false);
        }
        else
        {
            Bundle bundle = new Bundle();
            bundle.putString(FILE_URL_TAG , url);
            start(context,bundle,false);
        }
    }

    public static void start(Activity mContext, Bundle bundle, boolean isFinish)
    {
        Intent intent = new Intent();
        intent.setClass(mContext, FileReaderActivity.class);
        if (bundle != null)
            intent.putExtra(mContext.getPackageName(), bundle);
        mContext.startActivity(intent);
        if (isFinish)
        {
            mContext.finish();
        }
    }

    public Bundle getBundle()
    {
        if (getIntent() != null && getIntent().hasExtra(getPackageName()))
            return getIntent().getBundleExtra(getPackageName());
        else
            return null;
    }


    @Override
    protected int getLayoutId()
    {
        return R.layout.activity_file_reader;
    }

    @Override
    protected void initView()
    {
        Bundle mBundle = getBundle();
        if( mBundle != null )
        {
            fileUrl = mBundle.getString(FILE_URL_TAG,"");
            LogUtils.eTag("FileViewActivity" , fileUrl );
        }

        setToolbarTitle(viewDataBinding.includeTitle.toolbar,getString(R.string.file_tag));
        setToolBar(viewDataBinding.includeTitle.toolbar);

        // 当全局 多状态页面 不满足 显示需求时 可以自定义 一个 loadser
        /*
        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new EmptyCallback())
                .addCallback(new ErrorCallback())
                .build();
        loadSer = loadSir.register(viewDataBinding.llRootView,v -> { onRetryBtnClick(); });
        loadSer.showCallback( EmptyCallback.class );
        */
        setLoadSir(this);

    }

    @Override
    protected void initData()
    {

        showContent();

        if( !TextUtils.isEmpty( fileUrl ) )
        {
            openFile( fileUrl );
        }

        /*
        Flowable.create(emitter -> {
            emitter.onNext("test1.pdf");
            emitter.onComplete();
        }, BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe( fileName -> {
                            if( !getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).exists() )
                            {
                                getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).mkdir();
                            }
                            AssetsCopyUtil.copyAssetsFile(this,getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath(), (String) fileName);
                        }
                        , throwable -> {

                        } ,()->{

                            //File docFile = new File( );
                            //文件路径
                            viewDataBinding.fileReaderView.show( getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath()+"/test1.pdf" );
                        } );
        */


        //XDiskCache.getInstance().save(fileUri, filePath);

    }

    private void openFile(String fileUri)
    {
        if (!TextUtils.isEmpty(fileUri))
        {
            //是网络文件
            if (fileUri.contains("http") || fileUri.contains("https"))
            {
                String cacheFilePath = XDiskCache.getInstance().load(fileUri);
                //文件缓存存在
                if (!TextUtils.isEmpty(cacheFilePath) && FileUtils.isFileExists(cacheFilePath))
                {
                    viewDataBinding.fileReaderView.show(cacheFilePath);
                }
                else
                {
                    //没有缓存，下载
                    startDownload(viewDataBinding.fileReaderView, fileUri);
                }
            }
            else
            {
                viewDataBinding.fileReaderView.show(fileUri);
            }
        }
        else
        {
            ToastUtils.showShort("文件路径无效！");
        }
    }

    /**
     * 开始下载
     *
     * @param fileUri
     */
    private void startDownload(final FileReaderView fileReaderView, final String fileUri)
    {
        OkHttpUtils.get()
                .url(fileUri)
                .build()
                .execute(new FileCallBack(fileReaderView.getCacheFileDir(), fileReaderView.getFileNameByUrl(fileUri))
                {
                    @Override
                    public void onBefore(Request request, int id)
                    {
                        //getMessageLoader("文件下载中...").show();
                        showLoading();
                    }

                    @Override
                    public void inProgress(float progress, long total, int id)
                    {
                        LogUtils.e( "文件下载中(" + ((int) (progress * 100)) + "%)" );
                        //getMessageLoader().updateMessage("文件下载中(" + ((int) (progress * 100)) + "%)");
                    }

                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        showFailure( "文件下载失败" );
                        //getMessageLoader().dismiss();
                    }

                    @Override
                    public void onResponse(File response, int id)
                    {
                        //getMessageLoader().dismiss();
                        //保存缓存文件的路径
                        String filePath = response.getPath();
                        XDiskCache.getInstance().save(fileUri, filePath);
                        fileReaderView.show(filePath);
                    }
                });
    }



    public void change(View view)
    {
        /*
         * viewModel.changeText().observe(this, aBoolean -> { if( aBoolean ) {
         * viewModel.username.set("改变"); } });
         */
        showLoading();
        //mLoadService.showCallback(AnimateCallback.class);
        viewModel.getInfoByNet("1").observe(this, result -> {
            //showContent();
            mLoadService.showCallback(TimeoutCallback.class);
            viewModel.username.set(result);
        });

    }

    @Override
    protected int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void onRetryBtnClick()
    {
        Snackbar.make(viewDataBinding.getRoot(), "点击重试", Snackbar.LENGTH_LONG).show();
    }

    private void setToolbarTitle(Toolbar toolbar, String title)
    {
        //toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.red));

        ((TextView)toolbar.findViewById(R.id.tv_title)).setText( title );
        ((ImageButton)toolbar.findViewById(R.id.btn_back)).setImageResource(R.drawable.svg_back);
        toolbar.findViewById(R.id.btn_back).setOnClickListener( v -> {
            supportFinishAfterTransition();
        } );
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();

        viewDataBinding.fileReaderView.stop();

    }
}
